<template>
  <div class="store-delivery">
    <el-card>
      <template #header>
        <div class="card-header">
          <span class="title">🚚 门店配送管理</span>
          <div class="header-actions">
            <el-button type="primary" @click="handleAddTask">
              <el-icon><Plus /></el-icon>
              新建配送任务
            </el-button>
          </div>
        </div>
      </template>

      <!-- 搜索区域 -->
      <el-form :inline="true" class="search-form">
        <el-form-item label="配送门店">
          <el-select v-model="searchForm.storeId" placeholder="请选择门店" clearable>
            <el-option label="深圳旗舰店" value="1" />
            <el-option label="上海陆家嘴店" value="2" />
            <el-option label="北京国贸店" value="3" />
            <el-option label="广州天河店" value="4" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable>
            <el-option label="待发货" value="pending" />
            <el-option label="配送中" value="delivering" />
            <el-option label="已送达" value="delivered" />
            <el-option label="已取消" value="cancelled" />
          </el-select>
        </el-form-item>
        <el-form-item label="配送日期">
          <el-date-picker
            v-model="searchForm.dateRange"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="YYYY-MM-DD"
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">查询</el-button>
          <el-button @click="handleReset">重置</el-button>
        </el-form-item>
      </el-form>

      <!-- 统计卡片 -->
      <el-row :gutter="20" class="stat-cards">
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);">
              <el-icon :size="32"><Van /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">配送总数</div>
              <div class="stat-value">{{ totalDeliveries }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);">
              <el-icon :size="32"><Clock /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">待发货</div>
              <div class="stat-value pending">{{ pendingCount }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);">
              <el-icon :size="32"><Promotion /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">配送中</div>
              <div class="stat-value delivering">{{ deliveringCount }}</div>
            </div>
          </div>
        </el-col>
        <el-col :xs="12" :sm="6">
          <div class="stat-card">
            <div class="stat-icon" style="background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);">
              <el-icon :size="32"><CircleCheck /></el-icon>
            </div>
            <div class="stat-content">
              <div class="stat-label">已送达</div>
              <div class="stat-value delivered">{{ deliveredCount }}</div>
            </div>
          </div>
        </el-col>
      </el-row>

      <!-- 配送列表 -->
      <el-table :data="tableData" border stripe>
        <el-table-column prop="taskNo" label="任务编号" width="150" />
        <el-table-column prop="storeName" label="配送门店" width="150" />
        <el-table-column prop="productCount" label="商品数量" width="100" align="center" />
        <el-table-column prop="totalAmount" label="配送金额" width="120" align="right">
          <template #default="{ row }">
            <span class="amount-text">¥{{ row.totalAmount.toLocaleString() }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="driverName" label="配送员" width="100" />
        <el-table-column prop="driverPhone" label="联系电话" width="130" />
        <el-table-column prop="vehicleNo" label="车牌号" width="120" />
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column prop="deliveryTime" label="配送时间" width="160" />
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">
              {{ getStatusText(row.status) }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="250" fixed="right">
          <template #default="{ row }">
            <el-button link type="primary" @click="handleViewDetail(row)">详情</el-button>
            <el-button 
              v-if="row.status === 'pending'" 
              link 
              type="success" 
              @click="handleDeliver(row)"
            >
              发货
            </el-button>
            <el-button 
              v-if="row.status === 'delivering'" 
              link 
              type="warning" 
              @click="handleComplete(row)"
            >
              完成
            </el-button>
            <el-button link type="danger" @click="handleCancel(row)">取消</el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <el-pagination
        v-model:current-page="pagination.page"
        v-model:page-size="pagination.size"
        :total="pagination.total"
        :page-sizes="[10, 20, 50, 100]"
        layout="total, sizes, prev, pager, next, jumper"
        @size-change="handleSearch"
        @current-change="handleSearch"
      />
    </el-card>

    <!-- 新建配送任务对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      title="新建配送任务"
      width="700px"
    >
      <el-form :model="formData" :rules="formRules" ref="formRef" label-width="100px">
        <el-form-item label="配送门店" prop="storeId">
          <el-select v-model="formData.storeId" placeholder="请选择门店" style="width: 100%">
            <el-option label="深圳旗舰店" value="1" />
            <el-option label="上海陆家嘴店" value="2" />
            <el-option label="北京国贸店" value="3" />
            <el-option label="广州天河店" value="4" />
          </el-select>
        </el-form-item>

        <el-form-item label="配送商品">
          <el-button type="primary" size="small" @click="handleAddProduct">添加商品</el-button>
          <el-table :data="formData.products" border style="margin-top: 10px;">
            <el-table-column prop="productName" label="商品名称" />
            <el-table-column prop="quantity" label="数量" width="100" align="center" />
            <el-table-column prop="price" label="单价" width="100" align="right">
              <template #default="{ row }">
                ¥{{ row.price }}
              </template>
            </el-table-column>
            <el-table-column label="操作" width="80">
              <template #default="scope">
                <el-button link type="danger" @click="handleRemoveProduct(scope.$index)">
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-form-item>

        <el-form-item label="配送员" prop="driverName">
          <el-input v-model="formData.driverName" placeholder="请输入配送员姓名" />
        </el-form-item>

        <el-form-item label="联系电话" prop="driverPhone">
          <el-input v-model="formData.driverPhone" placeholder="请输入联系电话" />
        </el-form-item>

        <el-form-item label="车牌号" prop="vehicleNo">
          <el-input v-model="formData.vehicleNo" placeholder="请输入车牌号" />
        </el-form-item>

        <el-form-item label="预计送达" prop="deliveryTime">
          <el-date-picker
            v-model="formData.deliveryTime"
            type="datetime"
            placeholder="选择日期时间"
            value-format="YYYY-MM-DD HH:mm:ss"
            style="width: 100%"
          />
        </el-form-item>

        <el-form-item label="备注">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Plus, Van, Clock, Promotion, CircleCheck
} from '@element-plus/icons-vue'

// 搜索表单
const searchForm = reactive({
  storeId: '',
  status: '',
  dateRange: []
})

// 统计数据
const totalDeliveries = ref(456)
const pendingCount = ref(23)
const deliveringCount = ref(15)
const deliveredCount = ref(418)

// 表格数据
const tableData = ref([
  {
    id: 1,
    taskNo: 'DT202401001',
    storeName: '深圳旗舰店',
    productCount: 25,
    totalAmount: 156789,
    driverName: '李师傅',
    driverPhone: '13800138001',
    vehicleNo: '粤B12345',
    createTime: '2024-01-15 09:00:00',
    deliveryTime: '2024-01-15 14:30:00',
    status: 'delivered'
  },
  {
    id: 2,
    taskNo: 'DT202401002',
    storeName: '上海陆家嘴店',
    productCount: 18,
    totalAmount: 98765,
    driverName: '王师傅',
    driverPhone: '13800138002',
    vehicleNo: '沪A67890',
    createTime: '2024-01-15 10:00:00',
    deliveryTime: '2024-01-15 16:00:00',
    status: 'delivering'
  },
  {
    id: 3,
    taskNo: 'DT202401003',
    storeName: '北京国贸店',
    productCount: 32,
    totalAmount: 234567,
    driverName: '张师傅',
    driverPhone: '13800138003',
    vehicleNo: '京A11111',
    createTime: '2024-01-15 11:00:00',
    deliveryTime: '2024-01-16 10:00:00',
    status: 'pending'
  },
  {
    id: 4,
    taskNo: 'DT202401004',
    storeName: '广州天河店',
    productCount: 15,
    totalAmount: 87654,
    driverName: '陈师傅',
    driverPhone: '13800138004',
    vehicleNo: '粤A22222',
    createTime: '2024-01-15 12:00:00',
    deliveryTime: '2024-01-15 18:00:00',
    status: 'delivered'
  }
])

// 分页
const pagination = reactive({
  page: 1,
  size: 10,
  total: 4
})

// 对话框
const dialogVisible = ref(false)
const formRef = ref(null)

// 表单数据
const formData = reactive({
  storeId: '',
  products: [],
  driverName: '',
  driverPhone: '',
  vehicleNo: '',
  deliveryTime: '',
  remark: ''
})

// 表单验证规则
const formRules = {
  storeId: [{ required: true, message: '请选择配送门店', trigger: 'change' }],
  driverName: [{ required: true, message: '请输入配送员姓名', trigger: 'blur' }],
  driverPhone: [
    { required: true, message: '请输入联系电话', trigger: 'blur' },
    { pattern: /^1[3-9]\d{9}$/, message: '请输入有效的手机号', trigger: 'blur' }
  ],
  vehicleNo: [{ required: true, message: '请输入车牌号', trigger: 'blur' }]
}

// 获取状态标签
const getStatusTag = (status) => {
  const map = {
    pending: 'info',
    delivering: 'warning',
    delivered: 'success',
    cancelled: 'danger'
  }
  return map[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const map = {
    pending: '待发货',
    delivering: '配送中',
    delivered: '已送达',
    cancelled: '已取消'
  }
  return map[status] || status
}

// 搜索
const handleSearch = () => {
  console.log('搜索:', searchForm)
  ElMessage.success('查询成功')
}

// 重置
const handleReset = () => {
  searchForm.storeId = ''
  searchForm.status = ''
  searchForm.dateRange = []
  handleSearch()
}

// 新建任务
const handleAddTask = () => {
  Object.assign(formData, {
    storeId: '',
    products: [],
    driverName: '',
    driverPhone: '',
    vehicleNo: '',
    deliveryTime: '',
    remark: ''
  })
  dialogVisible.value = true
}

// 添加商品
const handleAddProduct = () => {
  formData.products.push({
    productName: 'iPhone 15 Pro Max',
    quantity: 10,
    price: 9999
  })
}

// 删除商品
const handleRemoveProduct = (index) => {
  formData.products.splice(index, 1)
}

// 查看详情
const handleViewDetail = (row) => {
  ElMessage.info(`查看配送任务：${row.taskNo}`)
}

// 发货
const handleDeliver = (row) => {
  ElMessageBox.confirm(`确定要发货任务 "${row.taskNo}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('发货成功')
    handleSearch()
  })
}

// 完成
const handleComplete = (row) => {
  ElMessageBox.confirm(`确定要完成任务 "${row.taskNo}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('配送完成')
    handleSearch()
  })
}

// 取消
const handleCancel = (row) => {
  ElMessageBox.confirm(`确定要取消任务 "${row.taskNo}" 吗？`, '提示', {
    type: 'warning'
  }).then(() => {
    ElMessage.success('任务已取消')
    handleSearch()
  })
}

// 提交表单
const handleSubmit = () => {
  formRef.value.validate((valid) => {
    if (valid) {
      if (formData.products.length === 0) {
        ElMessage.warning('请添加配送商品')
        return
      }
      console.log('提交表单:', formData)
      ElMessage.success('创建成功')
      dialogVisible.value = false
      handleSearch()
    }
  })
}
</script>

<style scoped>
.store-delivery {
  padding: 20px;
  background: #f5f5f5;
  min-height: 100vh;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.search-form {
  margin-bottom: 20px;
}

/* 统计卡片 */
.stat-cards {
  margin-bottom: 20px;
}

.stat-card {
  display: flex;
  align-items: center;
  padding: 20px;
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.05);
  transition: transform 0.3s;
}

.stat-card:hover {
  transform: translateY(-5px);
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  margin-right: 15px;
}

.stat-content {
  flex: 1;
}

.stat-label {
  font-size: 14px;
  color: #909399;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: bold;
  color: #303133;
}

.stat-value.pending {
  color: #909399;
}

.stat-value.delivering {
  color: #e6a23c;
}

.stat-value.delivered {
  color: #67c23a;
}

.amount-text {
  color: #f56c6c;
  font-weight: bold;
}

.el-pagination {
  margin-top: 20px;
  justify-content: flex-end;
}
</style>

